﻿/*
 * Copyright (c) 2011, The Chancellor, Masters and Scholars of the University of Oxford
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are 
 * permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this list of 
 *   conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice, this list 
 *   of conditions and the following disclaimer in the documentation and/or other 
 *   materials provided with the distribution.
 *
 * Neither the name of University of Oxford nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior 
 * written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using System.IO;
using System.Collections.ObjectModel;


namespace GroupMetadata
{
    public partial class MainPage : UserControl
    {

    #region AndrewCode1

        public ClientContext ClientCtx
        {
            get;
            set;
        }

        public List DCMList
        {
            get;
            set;
        }

        public string DCMLibrary
        {
            get;
            set;
        }

        public ListItemCollection DCMListItems
        {
            get;
            set;
        }

        public ObservableCollection<string> DCMFilenames
        {
            get;
            set;
        }

#endregion

        public MainPage()
        {
            InitializeComponent();
            DCMFilenames = new ObservableCollection<string>();
            //FileDetails.ItemsSource = DCMFilenames;
            foreach(var file_name in DCMFilenames) {
                txtOutputArea.Text += file_name + "\n";
            }
        }

        #region AndrewCode2

        public MainPage(string DCMLibraryPath)
        {
            DCMLibrary = DCMLibraryPath;
            InitializeComponent();
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            ClientCtx = new ClientContext(ApplicationContext.Current.Url);
            DCMList = ClientCtx.Web.Lists.GetByTitle(DCMLibrary);

            FillFileList();
        }

        private void FillFileList()
        {
            CamlQuery camlQuery = new CamlQuery();
            DCMListItems = DCMList.GetItems(camlQuery);
            ClientCtx.Load(DCMListItems,
                  items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.File));

            ClientCtx.ExecuteQueryAsync(LoadSiteData, FailLoadSiteData);
        }

        
        private void FailLoadSiteData(object sender, ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        MessageBox.Show(e.Message);
                    }
                )
            );
        }
        private void LoadSiteData(object Sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        try
                        {
                            if (DCMFilenames == null)
                            {
                                DCMFilenames = new ObservableCollection<string>();
                            }
                            foreach (var d in DCMListItems)
                            {
                                DCMFilenames.Add(d.File.Name.Split('.')[0]);
                            }
                            //FileDetails.ItemsSource = null;
                            //FileDetails.ItemsSource = DCMFilenames.Distinct().OrderBy(i => i);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButton.OK);
                        }
                    }
                )
            );
        }

        

        private void FileDetails_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
                Microsoft.SharePoint.Client.File clFileToUpload = null;
                foreach (var fi in files)
                {
                    var fciFileToUpload = new FileCreationInformation();
                    using (Stream streamToUpload = fi.OpenRead())
                    {
                        int length = (int)streamToUpload.Length;  // get file length
                        fciFileToUpload.Content = new byte[length];
                        int count = 0;                        // actual number of bytes read
                        int sum = 0;                          // total number of bytes read
                        while ((count = streamToUpload.Read(fciFileToUpload.Content, sum, length - sum)) > 0)
                        {
                            sum += count;  // sum is a buffer offset for next reading
                        }
                    }
                    fciFileToUpload.Overwrite = true;
                    fciFileToUpload.Url = fi.Name;
                    clFileToUpload = DCMList.RootFolder.Files.Add(fciFileToUpload);

                    ClientCtx.Load(clFileToUpload);
                    ClientCtx.ExecuteQueryAsync(OnLoadingSucceeded, OnLoadingFailed);
                }
            }
        }

        private void OnLoadingSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        FillFileList();
                    }
                )
            );
        }

        private void OnLoadingFailed(object sender, ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        MessageBox.Show(e.Message);
                    }
                )
            );
        }
    
    #endregion 
     

       Web oWebsite;
        ListCollection collList;
        IEnumerable<List> listInfo;


        private void btnLoadMetadataXml_Click(object sender, RoutedEventArgs e)
        {
            ClientContext clientContext = ClientContext.Current;
            oWebsite = clientContext.Web;
            ListCollection collList = oWebsite.Lists;

            clientContext.Load(oWebsite,
               website => website.Title);

            listInfo = clientContext.LoadQuery(
               collList.Include(
                   list => list.Title,
                   list => list.Fields.Include(
                       field => field.Title).Where(
                       field => field.Required == true
                       && field.Hidden != true)));

            clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);

            

        }



        private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayInfo;
            this.Dispatcher.BeginInvoke(updateUI);
        }

        private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }

        private void DisplayInfo()
        {
            txtOutputArea.Text = "Title: " + oWebsite.Title;
            collList = oWebsite.Lists;

            foreach (List oList in listInfo)
            {
                txtOutputArea.Text += "\n\tList: " + oList.Title;

                FieldCollection collField = oList.Fields;
                foreach (Field oField in collField)
                {
                    txtOutputArea.Text += "\n\t\tField: " + oField.Title;
                }
            }
        }

        private delegate void UpdateUIMethod();

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
